<template>
    <div class="flex wh-full">
        <div class="w-20% b-r-1px color-#999 b-r-dotted mr-20px pr-20px overflow-auto pt-20px" v-infinite-scroll="loadChatRoom" :infinite-scroll-disabled="data.isLoadChatRoom">
            <div class="p-10px  shadow mb-10px cursor-pointer relative"
                 :class="chatRoom.uuid === data.currentChatRoomUuid ? 'bg-#ddd' : ''"
                 v-for="chatRoom in data.chatRooms" :key="chatRoom.uuid" @click="selectChat(chatRoom)">
                <el-tag round effect="dark" size="small" type="danger" class="absolute right--5px top--5px">11</el-tag>
                <div class="flex-y-center justify-between">
                    <div class="flex-y-center">
                        <el-avatar
                            :src="chatRoom.userAvatar"
                        />
                        <span class="pl-10px">{{ chatRoom.nickName }}</span>
                    </div>
                    <span>{{ chatRoom.latestChatTime }}</span>
                </div>
                <div class="ellipsis-text pt-10px">
                    {{ chatRoom.latestChatMessage }}
                </div>
            </div>
        </div>
        <div class="flex-1 flex-col">
            <div class="flex-1 flex-col shadow mb-20px overflow-hidden">
                <div class="flex-center py-5px">{{ data.currentChatRoom.nickName }}</div>
                <div class="flex-1 overflow-auto" v-infinite-scroll="load" id="content">
                    <div v-for="chatMessage in data.chatMessages" :key="chatMessage.uuid">
                        <div>
                            <div class="time">{{chatMessage.sendTime}}</div>
                            <div class="comm-block" :class="chatMessage.sendAdminUuid === data.currentUserInfo.uuid ? 'right' : ''">
                                <el-avatar
                                    :src="chatMessage.sendAdminUuid === data.currentUserInfo.uuid ? 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' : chatMessage.userAvatar "
                                />
                                <div class="content">
                                    {{chatMessage.content}}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div>
                <el-input
                    v-model="data.content"
                    :rows="10"
                    type="textarea"
                    placeholder="请输入内容"
                    @keydown.enter="sendMessage"
                />
            </div>
        </div>
    </div>
</template>

<script>
import {reactive, onMounted} from "vue";
import {pageChatRoom, pageHistory} from "@/api/contactAdmin/contactAdmin";
import {getUserInfo} from "@/utils/auth";
import {ElMessage} from "element-plus";
let socket
export default {
    setup() {
        const data = reactive({
            chatRooms: [],
            // 当前聊天室uuid
            currentChatRoomUuid: '',
            // 当前聊天室
            currentChatRoom: '',
            chatMessages: [],
            currentUserInfo: getUserInfo(),
            charSocketUrl: process.env.VUE_APP_CURRENTMODE === 'development' ? 'ws://localhost:8002' : 'ws://192.168.1.2:8002',
            isDisableLoadChatRoom: false
        })
        const selectChat = (chatRoom) => {
            data.currentChatRoomUuid = chatRoom.uuid
            data.currentChatRoom = chatRoom
            pageHistory(data.currentChatRoomUuid).then(res => {
                data.chatMessages = res.data.records
            })
            scroll()
            init()
        }
        const sendMessage = () => {
            const sendParam = {
                content: data.content,
                sendUserUuid: data.currentUserInfo.uuid,
                receiveUserUuid: data.currentChatRoom.userUuid,
                roomId: data.currentChatRoomUuid,
                contentType: 1,
                isAdmin: true
            }
            socket.send(JSON.stringify(sendParam))
            data.content = ''
            scroll()
        }
        const loadChatRoom = () => {
            contactAdminChatRoomSearchParam.page++
            pageContactAdminChatRoom()
        }
        const contactAdminChatRoomSearchParam = reactive({
            page: 0,
            size: 10
        })
        // const contactAdminChatMessageSearchParam = reactive({
        //     page: 1,
        //     size: 10
        // })
        const pageContactAdminChatRoom = () => {
            pageChatRoom(contactAdminChatRoomSearchParam).then(res => {
                if (res.data.records.length < contactAdminChatRoomSearchParam.size){
                    data.isLoadChatRoom = true
                }
                data.chatRooms = res.data.records
            })
        }
        /**
         * 初始化聊天
         */
        const init = () => {
            if (typeof (WebSocket) === 'undefined') {
                ElMessage({
                    message: '您的浏览器不支持WebSocket',
                    type: 'error',
                })
            } else {
                let socketUrl = data.charSocketUrl + "/contactAdmin/websocket/one2one/" + data.currentUserInfo.uuid + "/" + data.currentChatRoomUuid
                if (socket != null) {
                    socket.close()
                    socket = null
                }
                socket = new WebSocket(socketUrl)
                socket.onopen = function () {
                    console.log("websocket已打开")
                }
                socket.onmessage = function (msg) {
                    const result = JSON.parse(msg.data)
                    const chatMessage = {
                        sendUserUuid: result.sendUserUuid,
                        sendUserAvatar: result.sendUserAvatar,
                        receiveUserUuid: result.receiveUserUuid,
                        sendAdminUuid: result.sendAdminUuid,
                        content: result.content,
                        contentType: result.contentType,
                        sendTime: result.createTime
                    }
                    data.chatMessages.push(chatMessage);
                    scroll()
                }
            }
        }
        const scroll = () => {
            setTimeout(() => {
                document.getElementById("content").scrollTo({
                    top: document.getElementById("content").scrollHeight,
                    behavior: "smooth"
                });
            }, 200)
        }
        onMounted(() => {
            // pageContactAdminChatRoom()
        })
        return {
            data,
            selectChat,
            sendMessage,
            loadChatRoom
        }
    }
}
</script>

<style scoped>
.time {
    text-align: center;
    padding: 10px 0;
}

.comm-block {
    display: flex;
    padding: 0 12px;
}

.comm-block.right {
    flex-direction: row-reverse;
}

.right .content {
    margin-right: 10px;
    margin-left: 0;
    background-color: antiquewhite;
}

.content {
    background-color: #94ede2;
    border-radius: 10px;
    /*flex: 1;*/
    padding: 10px;
    margin-left: 10px;
    word-break: break-all;
    max-width: 50%;
}

.avatar {
    flex: 0 0 40px;
}

.wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

.block {
    width: 120px;
    height: 120px;
}

.item {
    margin-top: 10px;
    margin-right: 40px;
}
</style>